<?php
/**
 * Created by PhpStorm.
 * User: 86151 - 姜伟
 * Date: 2022/9/5 14:09.
 */

namespace Xinyu\Gen\Core\Libs;

class ValidatorClient extends BaseClient
{
    use SingletonUtil;

    // 获取验证规则类型
    public function getRuleType($type = '', $comment = '', $length = 0)
    {
        switch ($type) {
            case 'integer':
            case 'smallint':
                return 'integer';
                break;
            case 'string':
                return "string|max:{$length}";
                break;
            case 'text':
                return 'string';
                break;
            case 'boolean':
                return $this->getBooleanRuleType($comment)['rule_type'];
                break;
            case 'datetime':
                return 'date_format:Y-m-d H:i:s';
                break;
            case 'decimal':
                return 'numeric';
                break;
            default:
                return '';
                break;
        }
    }

    // 获取字段说明
    public function getIntro($name = '', $comment = '')
    {
        $list = explode(' ', $comment, 2);
        return trim($list[0] ?? '') ?: $name;
    }

    // 获取过滤的字段
    public function getFilterFields()
    {
        return ['created_at', 'updated_at', 'deleted_at'];
    }

    // 获取boolean的规则类型(类似: is_draft: boolean: 是否是草稿 1=是草稿 0=非草稿 9=删除的)
    private function getBooleanRuleType($comment = '')
    {
        $list = explode(' ', $comment, 2);
        $intro = trim($list[0] ?? '');
        $remainComment = $list[1] ?? '';
        $remainList = explode(' ', $remainComment);
        $inList = [];
        if (!empty($remainList)) {
            foreach ($remainList as $v) {
                $itemList = explode('=', $v);
                if (2 === \count($itemList)) {
                    $inList[] = trim($itemList[0] ?? '');
                }
            }
        }
        sort($inList);
        $in = implode(',', $inList);
        $ruleType = "in:{$in}";
        return [
            'intro' => $intro,
            'rule_type' => $ruleType,
        ];
    }
}
